<?php

/**
 * @classname 用户
 * @classaccess public
 * @decription 用户接口
 * @author 张旭刚
 * @updateTime 2020年05月12日
 */

namespace employee\controllers;

use Yii;
use common\models\User;
use employee\models\Users;
use employee\models\Usertokens;

class UsersController extends PublicController {

    /**
     * @see 登录
     * @describe 登陆接口
     * @access public
     * @name login
     * @method POST
     * @requestType FORM
     * @defget no
     * @author 张旭刚,2020年07月03日,创建
     * 
     * @header guid|string|required|客户端唯一编号
     * 
     * @param username|string|required|用户名
     * @param password|string|required|密码
     * 
     * @return userToken|string|GUID
     * @return refreshToken|string|GUID
     */
    public function actionLogin(){
        $guid = $this->headers['guid'];
        $username = Yii::$app->request->post('username');
        $password = Yii::$app->request->post('password');
        if(empty($username)){
            return $this->renderJson(['code' => 0, 'result' => false, 'msg' => '用户名不能为空', 'errorCode' => 203001]);
        }
        if(empty($password)){
            return $this->renderJson(['code' => 0, 'result' => false, 'msg' => '密码不能为空', 'errorCode' => 203002]);
        }
        $user = User::findOne(['username' => $username, 'limitStr' => 'employee']);
        if(empty($user)){
            return $this->renderJson(['code' => 0, 'result' => false, 'msg' => '用户名或密码错误', 'errorCode' => 203004]);
        }
        if($user->validatePassword($password)){
            $this->user = $user;
            $this->userId = $user->id;
            $this->isLogin = true;
            $tokens = $this->createUserToken($user->username, $user->id, $user->email, $guid);
            return $this->renderJson(['code' => 1, 'result' => ['userToken' => $tokens->token, 'refreshToken' => $tokens->refreshToken, 'effective' => $this->setting('employee_login_token_limit_long')], 'msg' => '登录成功', 'errorCode' => 0]);
        }
        return $this->renderJson(['code' => 0, 'result' => false, 'msg' => '用户名或密码错误', 'errorCode' => 203005]);
    }

    /**
     * @see UserToken刷新
     * @describe UserToken刷新接口
     * @access public
     * @name user-refresh-token
     * @method POST
     * @requestType FORM
     * @defget no
     * @author 张旭刚,2020年07月03日,创建
     * 
     * @header guid|string|required|客户端唯一编号
     * 
     * @param refreshToken|string|required|刷新Token凭证
     * @param userToken|string|required|登录凭证
     * 
     * @return userToken|string|GUID
     * @return refreshToken|string|GUID
     * @return effective|string|登录令牌有效期
     */
    public function actionUserRefreshToken(){
        $guid = $this->headers['guid'];
        $refreshToken = Yii::$app->request->post('refreshToken');
        $token = Yii::$app->request->post('userToken');
        $tokens = Usertokens::findOne(['token' => $token, 'refreshToken' => $refreshToken]);
        $refreshTokenLimitLong = $this->setting('employee_login_refresh_token_limit_long');
        if(empty($tokens)){
            return $this->renderJson(['code' => 0, 'result' => false, 'msg' => '刷新凭证无效', 'errorCode' => 203003]);
        }
        if(time() - $tokens->ctime > $refreshTokenLimitLong){
            return $this->renderJson(['code' => 0, 'result' => false, 'msg' => '刷新凭证无效', 'errorCode' => 203004]);
        }
        $m = $this->createUserToken($tokens->username, $tokens->userid, $tokens->email, $guid);
        $data = ['userToken' => $m->token, 'refreshToken' => $m->refreshToken, 'effective' => $this->setting('employee_login_token_limit_long')];
        return $this->renderJson(['code' => 1, 'result' => $data, 'msg' => '刷新成功', 'errorCode' => 0]);
    }

    /**
     * @see 登出
     * @describe 登出接口
     * @access public
     * @name user-exit
     * @method POST
     * @requestType FORM
     * @defget no
     * @author 张旭刚,2020年07月03日,创建
     * 
     * @header guid|string|required|客户端唯一编号
     * @header userToken|string|required|登录证书
     * 
     * @return result|string|退出状态（成功/失败:true/false）
     */
    public function actionUserExit(){
        $result = Usertokens::find()->where(['userid' => $this->userId])->one()->delete();
        if($result){
            return $this->renderJson(['code' => 1, 'result' => ['result' => true], 'msg' => '退出成功', 'errorCode' => 0]);
        }
        return $this->renderJson(['code' => 0, 'result' => ['result' => false], 'msg' => '退出失败', 'errorCode' => 203005]);
    }

    private function createUserToken($username, $userid, $email, $guid){
        $m = Usertokens::findOne(['userid' => $userid]);
        if(empty($m)){
            $m = new Usertokens();
        }
        $m->userid = $userid;
        $m->username = $username;
        $m->email = $email;
        $salt = $this->setting('employee_login_salt');
        $tokenBase = $guid . '_' . $username . '_' . $userid . '_' . microtime();
        $refreshTokenBase = $username . '_' . $userid .'_'.$guid.'_'.microtime().'_'.rand(100000, 999999);
        $m->token = $this->sha256($tokenBase, $salt);
        $m->refreshToken = $this->sha256($refreshTokenBase, $salt);
        $m->ctime = time();
        $m->save(false);
        return $m;
    }
}
